﻿using Goooodbye.Core.Entities;
using Goooodbye.Core.Models.Query;
using Goooodbye.Core.Services;
using System;
using System.Windows.Forms;
using Goooodbye.Presentation.WinFormsApp.Properties;
using Goooodbye.Presentation.WinFormsApp.UserControls;
using Goooodbye.Core.Models;

namespace Goooodbye.Presentation.WinFormsApp
{
    public partial class FormDictionary : FormBase
    {
        private DictQuery query = new DictQuery();
        private IDictService dictService;
        private IImportService dictImportService;
        private IExportService<DictModel> dictExportService;

        public FormDictionary(IDictService dictService, IImportService dictImportService, IExportService<DictModel> dictExportService)
        {
            InitializeComponent();

            this.dictService = dictService;
            this.dictImportService = dictImportService;
            this.dictExportService = dictExportService;

            query.PageSize = Settings.Default.PageSize;
            query.PageNum = this.pagination1.PageNumber;
        }

        private void FormDictionary_Load(object sender, EventArgs e)
        {
            this.dataGridView1.AutoGenerateColumns = false;
            DataBind();
        }

        private void pagination1_PageUp(object sender, PageUpEventArgs e)
        {
            query.PageNum = e.PageNumber;
            DataBind();
        }

        private void pagination1_PageDown(object sender, PageDownEventArgs e)
        {
            query.PageNum = e.PageNumber;
            DataBind();
        }

        private void pagination1_PageNumberChanged(object sender, PageNumberChangedEventArgs e)
        {
            query.PageNum = e.PageNumber;
            DataBind();
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex >= 4)
            {
                var id = Convert.ToString(this.dataGridView1.Rows[e.RowIndex].Cells["ColId"].Value);
                switch (e.ColumnIndex)
                {
                    case 4: // edit
                        ShowFormDictionaryEdit(dictService.Get(id));
                        break;
                    case 5: // delete
                        string term = this.dataGridView1.Rows[e.RowIndex].Cells["ColTerm"].Value.ToString();
                        if (MessageBox.Show($"确实要把此词条删除吗？\r\n{term}", "删除词条", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            if (dictService.Remove(id))
                            {
                                DataBind();
                            }
                            else
                            {
                                MessageBox.Show("删除时发生异常", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        break;
                    default:
                        return;
                }
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            FormDictionaryImport frm = new FormDictionaryImport(dictService, dictImportService);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                DataBind();
            }
        }

        private void btnExportAll_Click(object sender, EventArgs e)
        {
            try
            {
                this.saveFileDialog1.DefaultExt = Settings.Default.DefaultExt;
                this.saveFileDialog1.Filter = Settings.Default.DefaultExt == "csv"
                    ? "CSV UTF-8（逗号分隔）|*.csv"
                    : "文本文件（逗号分隔）|*.txt";
                if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    var items = dictService.Query(new DictQuery() { Keyword = query.Keyword }).Items;
                    var count = dictExportService.Export(items, this.saveFileDialog1.FileName);
                    MessageBox.Show($"导出完成（{count} 条）", "导出", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnExportCurrent_Click(object sender, EventArgs e)
        {
            try
            {
                this.saveFileDialog1.DefaultExt = Settings.Default.DefaultExt;
                this.saveFileDialog1.Filter = Settings.Default.DefaultExt == "csv"
                    ? "CSV UTF-8（逗号分隔）|*.csv"
                    : "文本文件（逗号分隔）|*.txt";
                if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    var items = dictService.Query(query).Items;
                    var count = dictExportService.Export(items, this.saveFileDialog1.FileName);
                    MessageBox.Show($"导出完成（{count} 条）", "导出", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            ShowFormDictionaryEdit();
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            Query();
        }

        private void txtKeyword_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                Query();
            }
        }

        private void ShowFormDictionaryEdit(Dict entity = null)
        {
            FormDictionaryEdit frm = new FormDictionaryEdit(dictService);
            if (entity != null)
            {
                frm.Entity = entity;
            }
            if (frm.ShowDialog() == DialogResult.OK)
            {
                DataBind();
            }
        }

        private void Query()
        {
            query.PageNum = this.pagination1.PageNumber = 1;
            query.Keyword = this.txtKeyword.Text.Trim();
            DataBind();
        }

        private void DataBind()
        {
            query.SortOrder = "term";
            var list = dictService.Query(query);
            this.dataGridView1.DataSource = list.Items;
            this.pagination1.PageCount = list.PageCount;
            this.pagination1.TotalCount = list.Total;
        }
    }
}
